package com.wx.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class JsonUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger( JsonUtil.class );

    public static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 对象转换为json字符串
     * @param obj
     * @return
     */
    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj.getClass() == String.class) {
            return (String) obj;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.error("json序列化出错：" + obj, e);
            return null;
        }
    }

    public static <T> T toBean(String json, Class<T> tClass) {
        try {
            return mapper.readValue(json, tClass);
        } catch (IOException e) {
            LOGGER.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <E> List<E> toList(String json, Class<E> eClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
        } catch (IOException e) {
            LOGGER.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            LOGGER.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            LOGGER.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static String phpJsonEncode(Object obj) {
        String s = null;
        try {
            s = new ObjectMapper().writeValueAsString( obj );
        } catch (JsonProcessingException e) {
            LOGGER.error( "json序列化出错：" + obj, e );
        }
        s = s.replace( "/", "\\/" );
        s = chineseCharacterToUnicode( s );
        return s;
    }

    private static String chineseCharacterToUnicode(String str) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt( i );
            // 汉字范围 chr1 >= 19968 && chr1 <= 171941 (中文),这里大于127都转
            if (chr1 > 127) {
                result.append( "\\u" ).append( Integer.toHexString( chr1 ) );
            } else {
                result.append( str.charAt( i ) );
            }
        }
        return result.toString();
    }

    /**
     * Unicode转中文
     *
     * @param dataStr
     * @return
     */
    public static String decodeUnicode(final String dataStr) {
        if (!dataStr.contains( "\\u" )) {
            return dataStr;
        }
        int start = 0;
        int end = 0;
        StringBuilder stringBuilder = new StringBuilder();
        while (start > -1) {
            end = dataStr.indexOf( "\\u", start + 2 );
            String charStr;
            if (end == -1) {
                charStr = dataStr.substring( start + 2, dataStr.length() );
            } else {
                charStr = dataStr.substring( start + 2, end );
            }
            // 16进制parse整形字符串。
            char letter = (char) Integer.parseInt( charStr, 16 );
            stringBuilder.append( new Character( letter ).toString() );
            start = end;
        }
        return stringBuilder.toString();
    }
}
